package com.xms.schema.service.optionset;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xms.dependency.XmsDependencyException;
import com.xms.schema.entity.Attribute;
import com.xms.schema.entity.OptionSet;
import com.xms.schema.event.AttributeDeletedEvent;
import com.xms.schema.extension.AttributeExt;
import com.xms.utils.CollectionUtil;
import com.xms.utils.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 删除字段后，级联删除关联选项
 * </p>
 *
 * @author migo
 * @since 2021/10/26
 */
@Service
public class OptionSetCascadeDeleter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private IOptionSetDeleterService _optionSetDeleterService;
    private IOptionSetFinderService _optionSetFinderService;

    @Autowired
    public void OptionSetCascadeDeleter(IOptionSetDeleterService optionSetDeleterService,
                                        IOptionSetFinderService optionSetFinderService) {
        _optionSetDeleterService = optionSetDeleterService;
        _optionSetFinderService = optionSetFinderService;
    }

    public boolean cascadeDelete(Attribute... parent) throws SQLException, XmsDependencyException {
        if (CollectionUtil.isEmpty(parent)) {
            return false;
        }
        List<Attribute> attributes = Arrays.stream(parent).filter(x -> (AttributeExt.typeIsPickList(x) || AttributeExt.typeIsStatus(x)) && UUIDUtil.notEmpty(x.getOptionsetid())).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(attributes)) {
            return false;
        }
        List<UUID> ids = attributes.stream().map(x -> x.getOptionsetid()).collect(Collectors.toList());
        //删除字段关联的选项集，非公共的
        List<OptionSet> deleteds = _optionSetFinderService.list(new LambdaQueryWrapper<OptionSet>()
                .in(OptionSet::getOptionsetid, ids)
                .eq(OptionSet::getIspublic, false));
        if (CollectionUtil.notEmpty(deleteds)) {
            for (OptionSet deleted : deleteds) {
                _optionSetDeleterService.delete(deleted);
            }
            return true;
        }
        return false;
    }

    @Async
    @EventListener
    public void onApplicationEvent(AttributeDeletedEvent event) throws XmsDependencyException, SQLException {
        logger.info("OptionSetCascadeDeleting");
        this.cascadeDelete(event.source);
    }
}
